<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="100%" @ok="handleSubmit">

    <BasicForm @register="registerForm">
      <template #title_group="{ model, field }">
<!--        <vxe-grid ref="tableRef" v-bind="gridOptions" style="height: 300px;">-->
<!--          <template #toolbar_buttons>-->
<!--            <Button type="primary" size="small" @click="addFn">添加分类</Button>-->
<!--          </template>-->
<!--          <template #action="{ row }">-->
<!--            <TableAction outside :actions="getActions(row)" />-->
<!--          </template>-->
<!--        </vxe-grid>-->

        <div style="background: white;">
          <div style="border-top: 1px solid #e8eaec;">
            <Button type="primary" size="small" @click="addFn">添加分类</Button>
          </div>
          <div style="border-top: 1px solid #e8eaec;display: flex;">
            <div v-for="(item, index) in titleGroupColumnsRef" class="foot_item "  :style="getHeadStyle(item)" :key="index">
              <div class="foot_item_row" >
                {{item.title}}
              </div>
            </div>
          </div>
          <div  v-if="groupList.length > 0">
            <div v-for="(item2, index2) in groupList"  style="display: flex" :key="index2" >
               <div v-for="(item, index) in titleGroupColumnsRef" class=" foot_item "  :style="getHeadStyle(item)" :key="index">
<!--                 {{item2}}-->
                <div v-if="item2[item.field]!=null" class="foot_item_row">

                  <span v-if="item.formatter!=null" :style="{color:item.color}">

                    {{item.formatter({cellValue:item2[item.field],row:item2})}}
                  </span>
                  <span v-else>{{item2[item.field]}}</span>
                </div>
                <div v-if="item.title=='操作'" class="foot_item_row">
                  <TableAction outside :actions="getActions(item2,index2)" />
                </div>
              </div>

            </div>
            <div class="foot_item">
               <span style="padding-left: 10px"> 共: {{groupList.length}}条</span>
            </div>
          </div>
          <Empty v-if="groupList.length == 0"></Empty>

        </div>
      </template>

    </BasicForm>
    <ChooseQuestionDrawer @register="choose[0]" @success="handleSuccess"></ChooseQuestionDrawer>

  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, toRaw, reactive } from 'vue';
import { Button,Empty } from 'ant-design-vue';
import { BasicForm, useForm } from '@/components/Form';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useDrawer } from '@/components/Drawer';

import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';

import {
  formSchema,
  titleGroupColumns
} from './role.data';

import { BasicModal, useModalInner } from '@/components/Modal';
import { Form, FormItem, Input, InputNumber, DatePicker, Select, Switch } from 'ant-design-vue';
import ChooseQuestionDrawer from './ChoosePaperQuestionDrawer.vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { paperSave,paperDetail } from '@/api/heng/ex';
import { useMessage } from "@/hooks/web/useMessage";
import util from '@/utils/util';
const choose = useDrawer();

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();


const id = ref("")

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

// const tableRef = ref();

const dataList = ref({});
const groupList=ref([]);//{categoryName:"测试",type:1}

const titleGroupColumnsRef = ref(titleGroupColumns);



const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data.isUpdate;

  id.value = "";
  groupList.value=[];
  if (!isUpdate.value) {
    resetFields();
  } else {

    id.value = data.record.paperId;
    paperDetailFn();
  }


});

const getTitle = computed(() => ('试卷信息保存'));


function paperDetailFn(){
  setDrawerProps({ confirmLoading: true });

  paperDetail({paperId:id.value}).then((res) => {
    if(res.code==200){
      let json=res.data;
      dataList.value = json;
      groupList.value= json.groups;
      setFieldsValue(json);

    }else{
      createMessage.error(res.message);
    }
  }).finally(e=>{
    setDrawerProps({ confirmLoading: false });

  })


}

async function handleSubmit() {
  try {

    const values = await validate();
    values.paperId = id.value;
    let t_list = groupList.value;
    if (t_list.length == 0) {
      createMessage.error("请选择题目:添加题目分类>选题!");
      return;
    }
    values.groups = t_list;
    paperSave(values).then(res => {
      sunccFn(res)
    });


  } catch (e) {
    console.log(e)
  } finally {
    setDrawerProps({ confirmLoading: false });

  }
}

function sunccFn(result) {
  if (result && result.code == 200) {
    createMessage.success(result.message);
  } else {
    createMessage.error(result.message);
  }
  closeDrawer()
  emit('success');
}

function cancelFn() {
  //  tableRef.value.clearValidate();
}

function getHeadStyle(head){
  let style = {};
  if(head.width){
    style.width=head.width+'px';
  }else{
    style.flex=1;
  }
  return style;
}

function getActions(record,index) {
  let arr = [
    {
      // icon: 'clarity:note-edit-line',
      label: '编辑',
      onClick: handleEdit.bind(null, record,index),
    },
    {
      // icon: 'ant-design:delete-outlined',
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否删除？',
        placement: 'left',
        confirm: handleClose.bind(null, record,index),
      },
    }
  ];


  return arr;
}


function handleClose(record: Recordable,index) {
  let list = unref(groupList.value);
  list.splice(index,1);
   groupList.value =list;

}

async function addFn() {
  const values = await validate();

  choose[1].openDrawer(true, {
    isUpdate: false,
    limitTime:values.limitTime,
    ruleType:values.ruleType,

  })
}

function handleSuccess(item) {

  if(item.isUpdate) {
    groupList.value[item.index]=item;
  }else{
    groupList.value.push(item);
  }
}

async function handleEdit(record: Recordable,index) {
  record.isUpdate=true
  record.index = index;
  const values = await validate();
  record.ruleType=values.ruleType;

  choose[1].openDrawer(true, record)
}


</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}

.foot_item {
  display: flex;
  padding-top: 4px;
  padding-bottom: 2px;
  border-right: 1px solid #e8eaec;
  border-bottom: 1px solid #e8eaec;
  border-left: 1px solid #e8eaec;
  color: #606266;
}

.foot-c {
  justify-content: center;
  width: 100%;
}
.foot_item_row{
  width: 100%;
  text-align: center;
}
</style>
